import React, { useEffect } from "react";
import { Modal, Form, Input, Cascader, Space, Radio, Switch } from "antd";
import { modalPropsType } from "@/constants/types";
import { isEmptyObj } from "@/utils/util";
import { useModel } from "@umijs/max";
import { useComponentDidMount } from "@/hooks";

const {Item} = Form;
const rules = [{required: true}];
const labelCol = {span: 3};
const initValues = {isDefault: false};

const AddressUpdate = ({visible, onCancel, onSubmit, currentRow, title, loading}: modalPropsType) => {
  const [form] = Form.useForm();
  const { areaData, fetchAreaData } = useModel('areaModel');
  
  const handleSubmit = async () => {
    const res = await form.validateFields();
    onSubmit({
      ...res,
      id: currentRow?.id,
      province: res?.addressArea?.[0],
      city: res?.addressArea?.[1],
      area: res?.addressArea?.[2],
      addressArea: undefined,
      isDefault: res?.isDefault ? '1' : '0'
    });
  }

  useEffect(() => {
    if (!isEmptyObj(currentRow)) {
      form.setFieldsValue({
        ...currentRow,
        addressArea: [currentRow?.province, currentRow?.city, currentRow?.area],
        isDefault: currentRow?.isDefault === '1'
      });
    }
  }, [JSON.stringify(currentRow)]);

  useComponentDidMount(() => {
    fetchAreaData();
  });

  return (
    <Modal
      open={visible}
      title={title}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      maskClosable={false}
      width="750px"
    >
      <Form form={form} labelCol={labelCol} className="modal-form-padding" initialValues={initValues}>
        <Item label="联系人" name="contacts" rules={rules}>
          <Input />
        </Item>
        <Item label="联系电话" name="mobile" rules={rules}>
          <Input maxLength={11} />
        </Item>
        <Item label="地址" required>
          <Space>
            <Item noStyle name="addressArea" rules={[{required: true, message: '请选择地区'}]}>
              <Cascader showSearch style={{width: '250px'}} fieldNames={{label: 'name', value: 'name', children: 'children'}} options={areaData} />
            </Item>
            <Item noStyle name="address" rules={[{required: true, message: '请输入详细地址'}]}>
              <Input style={{width: '355px'}} />
            </Item>
          </Space>
        </Item>
        <Item label="是否默认" name="isDefault" rules={rules} valuePropName="checked">
          <Switch />
        </Item>
        <Item label="备注">
          <Input.TextArea rows={3} />
        </Item>
      </Form>
    </Modal>
  );
}
export default AddressUpdate;